﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace Tiscs.Practices
{
    /// <summary>
    /// 弱引用对象跟踪器。
    /// </summary>
    public static class ObjectTracker
    {
        /// <summary>
        /// 静态对象，用于锁定。
        /// </summary>
        private static readonly object monitor = new object();

        /// <summary>
        /// 被跟踪的对象弱引用列表。
        /// </summary>
        private static readonly List<WeakReference> objects = new List<WeakReference>();

        /// <summary>
        /// 跟踪一个对象。
        /// </summary>
        /// <param name="objectToTrack">要跟踪的对象。</param>
        public static void Track(object objectToTrack)
        {
            if (Debugger.IsAttached)
            {
                lock (monitor)
                {
                    objects.Add(new WeakReference(objectToTrack));
                }
            }
        }

        /// <summary>
        /// 获取所有活动的已跟踪对象。
        /// </summary>
        /// <returns>所有活动的已跟踪对象。</returns>
        public static IEnumerable<object> GetAllLiveTrackedObjects()
        {
            lock (monitor)
            {
                GC.Collect();
                return objects.Where(o => o.IsAlive).Select(o => o.Target);
            }
        }
    }

}
